package com.yz.jdd.webview.download;

import android.util.Log;

import com.tonyodev.fetch2.AbstractFetchListener;
import com.tonyodev.fetch2.Download;
import com.tonyodev.fetch2.Error;
import com.tonyodev.fetch2.Fetch;
import com.tonyodev.fetch2.FetchConfiguration;
import com.tonyodev.fetch2.Request;
import com.tonyodev.fetch2core.Func;
import com.tonyodev.fetch2okhttp.OkHttpDownloader;
import com.yz.jdd.base.MyApplication;


import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;

public class FetchUtil {

    public static void downLoadH5zip(String downLoadUrl) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .build();

        FetchConfiguration fetchConfiguration;
        fetchConfiguration = new FetchConfiguration.Builder(MyApplication.application)
                .setDownloadConcurrentLimit(3)
                .setHttpDownloader(new OkHttpDownloader(okHttpClient))
                .build();

        Fetch fetch = Fetch.Impl.getInstance(fetchConfiguration);
        fetch.deleteAll();
        URL mUrl = null;
        String fileName = "H5.zip";
        try {
            mUrl = new URL(downLoadUrl);
            fileName = new File(mUrl.getFile()).getName();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
//        Log.e("lkf", "------" + fileName);
        final String filePath = H5DownFileUtils._ZIP_FOLDERPATH + "/" + fileName;
        Request request = new Request(downLoadUrl, filePath);
        fetch.enqueue(request, new Func<Request>() {
            @Override
            public void call(@NotNull Request request) {

            }
        }, new Func<Error>() {
            @Override
            public void call(@NotNull Error error) {

            }
        });

        fetch.addListener(new AbstractFetchListener() {
            @Override
            public void onCompleted(Download download) {
                super.onCompleted(download);
                //com.yunzong.skylark/files/unzip//H5.zip
//                Log.e("lkf", "" + filePath);
                File zipFile = new File(filePath);
                boolean upZipSuccess = H5DownFileUtils.upZipFile(zipFile, H5DownFileUtils.DEFAULT_FOLDERPATH+"/", "");
                if (upZipSuccess) {
                    Log.e("lkf", "" + upZipSuccess);
                    android.os.Process.killProcess(android.os.Process.myPid());
                }
            }
        });
    }
}
